const express = require('express');
const router = express.Router();
const { success, failure } = require('../utils/response');
const { Course } = require('../models');
const {BadRequest} = require("http-errors")

// 获取分类中的所属课程
router.get("/",async(req,res)=>{
    try {
        const query = req.query;
        if(!query.categoryId){
            throw new BadRequest("缺少参数 categoryId");
        }
        const pageIndex = Math.abs(Number(query.pageIndex)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (pageIndex - 1) * pageSize;

        const condition = {
            where:{
                categoryId:query.categoryId
            },
            order:[["id","DESC"]],
            attributes:{exclude:['CategoryId','categoryId','UserId','userId','content']},
            limit:pageSize,
            
            offset
        }

        const {count,rows} = await Course.findAndCountAll(condition);
        const result = {
            pagination:{
                total:count,
                pageIndex,
                pageSize,
            },
            data:rows
        }
        success(res,"获取课程列表成功。",result);
    } catch (error) {
        failure(res, error);
    }
})

module.exports = router;